package com.kichina.parking.module.message.socket.message;

import com.alibaba.fastjson.JSONObject;
import com.kichina.parking.exception.extend.JsonParseException;
import com.kichina.parking.module.message.socket.IMessageHandler;
import com.kichina.parking.module.message.socket.SocketStorageDeal;
import com.kichina.parking.module.message.socket.bean.BaseSocketResponse;
import com.kichina.parking.module.message.socket.enums.MessageTypeEnum;
import com.kichina.parking.module.message.socket.exception.MessageDealException;
import com.kichina.parking.upstream.Parking2MonthPayUpstreamHandler;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Surging
 * @version 1.0
 * @ClassName SocketMessageMonthPayHandler
 * @date 2022-09-14 19:58
 * @desc 固定车收费后主动上传缴费信息到服务端
 */
@Component
@Order(Byte.MIN_VALUE + 3)
@Slf4j
public class MonthPayHandler implements IMessageHandler {

    private final Parking2MonthPayUpstreamHandler parking2MonthPayUpstreamHandler;

    public MonthPayHandler(Parking2MonthPayUpstreamHandler parking2MonthPayUpstreamHandler) {
        this.parking2MonthPayUpstreamHandler = parking2MonthPayUpstreamHandler;
    }

    @Override
    public void handler(JSONObject jsonObject, NetSocket netSocket) throws MessageDealException {
        try {
            //保存固定车收费后主动上传缴费信息
            parking2MonthPayUpstreamHandler.recordMonthPayUpstream(jsonObject);
        } catch (JsonParseException e) {
            if (Objects.nonNull(netSocket)){
                SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildFailedOrderId(jsonObject.getString("service"), jsonObject.getString("order_id")));
            }else {
                throw new MessageDealException("固定车收费后主动上传缴费业务处理发生异常");
            }
        }
        if (Objects.nonNull(netSocket)) {
            SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildSuccessOrderId(jsonObject.getString("service"), jsonObject.getString("order_id")));
        }
    }

    @Override
    public boolean check(JSONObject jsonObject) {
        return MessageTypeEnum.MONTH_PAY_RECORD.getValue().equals(jsonObject.getString("service"));
    }

    @Override
    public boolean interrupt() {
        return true;
    }
}
